package com.dican.portal.consultas;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dican.portal.DAO.ConsultaDAO;
import com.dican.portal.beans.Representante;

public class ConsultaPedidos extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public ConsultaPedidos() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String dateFrom=request.getParameter("dateFrom");
		String dateTo=request.getParameter("dateTo");
		String cliente=request.getParameter("cliente");
		String filtro="";
		Calendar myDate = Calendar.getInstance();
		if(!cliente.isEmpty())
			filtro = " AND (BP.value = '" + cliente + "' OR BP.taxid LIKE '%" + cliente + "%' OR UPPER(BP.name) LIKE UPPER('%" + cliente + "%')) ";
		else
		{
			if(dateFrom.isEmpty()){
		        myDate.add(Calendar.MONTH, 1);
		        dateTo = myDate.get(Calendar.YEAR)+"-"+myDate.get(Calendar.MONTH)+"-"+myDate.get(Calendar.DAY_OF_MONTH);
		        myDate.add(Calendar.MONTH, -2);
		        dateFrom = myDate.get(Calendar.YEAR)+"-"+myDate.get(Calendar.MONTH)+"-"+myDate.get(Calendar.DAY_OF_MONTH);
			}
		}
		
		if(dateFrom!="")
			filtro+=" AND OD.created >= '" + dateFrom + "' ";
		if(dateTo!="")
			filtro+=" AND OD.created <= '" + dateTo + "' ";
		HttpSession session = request.getSession(false);
		if(session==null)
			response.sendRedirect("logout.jsp");
		Representante rep = (Representante)session.getAttribute("rep");
		try
		{
			request.setAttribute("pedidos", ConsultaDAO.getPedidos(filtro,rep.getBpid()));
		}catch(SQLException e){
			out.print("SQL error "+e.getMessage());
		}catch(Exception e){
			out.print("Erro no FillCli.<br>Contate o Suporte da Dican e informe o seguinte erro:<br>"+e.getMessage());
		}
		RequestDispatcher view = request.getRequestDispatcher("pedidosAbsorvidos.jsp");
		view.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
